package com.qiantu.phone.ui.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.qiantu.api.entity.DeviceModeValue;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppAdapter;

import java.util.List;

public final class DeviceModeAdapter extends AppAdapter<DeviceModeValue> {

    private DeviceModeValue selected = null;
    public DeviceModeAdapter(Context context) {
        super(context);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder();
    }

    @Override
    public void setData(@Nullable List<DeviceModeValue> data) {
        super.setData(data);
        if(data != null && data.size() > 0){
            selected = data.get(0);
        }
    }

    private final class ViewHolder extends AppAdapter<?>.ViewHolder {

        private final TextView tvName;
        private final TextView checkView;

        private ViewHolder() {
            super(R.layout.item_device_mode);
            tvName = findViewById(R.id.tv_name);
            checkView = findViewById(R.id.check_view);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if(checkView.isSelected()){
                return;
            }
            checkView.setSelected(!checkView.isSelected());
            DeviceModeValue data = (DeviceModeValue) view.getTag();
            selected = data;
            notifyDataSetChanged();
            super.onClick(view);
        }

        @Override
        public void onBindView(int position) {
            DeviceModeValue deviceMode = getItem(position);
            int res = getResources().getIdentifier(deviceMode.getName(), "string", getContext().getPackageName());
            tvName.setText(res);
            itemView.setTag(deviceMode);
            if(selected != null && selected.equals(getItem(position))){
                checkView.setSelected(true);
            }else{
                checkView.setSelected(false);
            }
        }
    }

    public DeviceModeValue getSelected() {
        return selected;
    }

    public void checkSelected(DeviceModeValue selected){
        if(selected != null){
            this.selected = selected;
            notifyDataSetChanged();
        }
    }

    public DeviceModeValue checkSelected(int value){
        for(DeviceModeValue deviceMode : getData()){
            if(deviceMode.getValue() == value){
                this.selected = deviceMode;
                notifyDataSetChanged();
                return deviceMode;
            }
        }
        return null;
    }
}